<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { getLoginUserUsingGet, updateUserInfoUsingPut } from '@/api/userController.ts'
import AvatarUpload from '@/components/AvatarUpload.vue'
import emitter from '@/eventBus.ts'

const user = ref<API.UserVo>({})

// 修改信息
const updateUserInfo = async () => {
  if (!user.value.id) {
    return
  }
  const res: any = await updateUserInfoUsingPut(user.value)
  if (res.code === 200) {
    message.success('修改成功')
    // 发送登录成功事件
    emitter.emit('updateUserInfo')
  } else {
    message.error(res.message)
  }
}

// 获取登录用户信息
const getLoginUser = async () => {
  const res: any = await getLoginUserUsingGet()
  if (res.code === 200) {
    user.value = res.data
  } else {
    message.error(res.message)
  }
}

// 回调函数
const onSuccess = (newUserAvatar: string) => {
  user.value.userAvatar = newUserAvatar
}

onMounted(() => getLoginUser())
</script>

<template>
  <div id="user-center-view">
    <a-card title="修改信息" :bordered="true" class="card-style">
      <a-form :model="user">
        <a-form-item label="头像">
          <avatar-upload :user="user" :on-success="onSuccess" />
        </a-form-item>
        <a-form-item label="账号">
          <a-input v-model:value="user.userAccount" class="input-style" />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="user.userName" class="input-style" />
        </a-form-item>
        <a-form-item label="性别">
          <a-radio-group v-model:value="user.gender">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="年龄">
          <a-input-number
            style="width: 100%"
            v-model:value="user.age"
            :min="1"
            :max="100"
            class="input-style"
          />
        </a-form-item>
        <a-form-item
          label="手机号"
          prop="phone"
          :rules="[
            {
              required: true,
              message: '请输入手机号',
            },
            {
              pattern: /^(?:13[0-9]|14[5-9]|15[0-3,5-9]|17[0-3,6-9]|18[0-9]|19[0-3,5-9])\d{8}$/,
              message: '请输入正确的手机号',
            },
          ]"
        >
          <a-input v-model:value="user.phone" class="input-style" />
        </a-form-item>
        <a-form-item label="收货地址">
          <a-input v-model:value="user.address" class="input-style" />
        </a-form-item>
        <a-form-item>
          <a-button @click="updateUserInfo" type="primary" style="width: 400px">保存</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped>
#user-center-view {
  max-width: 720px;
  margin: 0 auto;
}
</style>
